class OffPromotionSubject
  include Mongoid::Document
  include Mongoid::Timestamps


  field :title, type: String
  field :layout_style, type: Integer, default: 1
  field :sequencing, type: Integer, default: 0



  validate :before_create_validation,:on=>:create
  validate :before_update_validation,:on=>:update

  attr_readonly *fields.keys

  def before_create_validation

    errors.add(:title, '请输入标题！') if self.title==""
    errors.add(:product_group_id, '请选择促销商品分组') if self.product_group_id.nil?
    errors.add(:product_group_id, '最多只能有三个主题！') if self.off_promotion.off_promotion_subjects.count>=3

  end


  def before_update_validation

    errors.add(:title, '请输入标题！') if self.title==""
    errors.add(:product_group_id, '请选择促销商品分组') if self.product_group_id.nil?

  end


  belongs_to :off_promotion

  belongs_to :product_group

  #同步该商品分组促销商品状态
  def syn_product_group(product_group_id)
    begin

      if self.product_group.present?

        self.product_group.off_promotion_subject_products.each do |off_promotion_subject_product|
          off_promotion_subject_product.update(:status => -1)
        end

      end

      product_group = ProductGroup.find(product_group_id)
      product_group.off_promotion_subject_products.each do |off_promotion_subject_product|
        off_promotion_subject_product.update(:start_time => self.off_promotion.begin_time, :end_time => self.off_promotion.end_time, :status => 0)
      end

      self.product_group_id = product_group.id
      self.save

      true
    rescue
      false
    end

  end

end
